const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const fs = require('fs')
const redisClient = require('./db/redis')
const session = require('express-session')
const RedisStore = require('connect-redis')(session)

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

if (process.env.NODE_ENV === 'dev') {
  app.use(logger('dev'));
} else {
  const writeStream = fs.createWriteStream(path.resolve(__dirname, './logs/access.log'), { flags: 'a' })
  app.use(logger('combined', {
    stream: writeStream
  }));
}

app.use(session({
  secret: 'hua-blog#_',
  cookie: {
    maxAge: 24 * 60 * 60 * 1000
  },
  store: new RedisStore({
    client: redisClient
  })
}))
app.use('/api/blog', require('./routes/blog'));
app.use('/api/user', require('./routes/user'));
app.use((req, res, next) => {
  next(createError(404));
});

app.use((err, req, res, next) => {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'dev' ? err : {};
  res.status(err.status || 500);
  // res.render('error');
  // res.send('error');
  // 仅仅作为服务，不需要渲染页面返回
  res.json({ error: err })
});

module.exports = app;
